package org.dfzt.modules.online.cgreport.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.dfzt.common.api.vo.Result;
import org.dfzt.common.aspect.annotation.PermissionData;
import org.dfzt.common.exception.SpringBootException;
import org.dfzt.common.system.service.ISysBaseAPI;
import org.dfzt.common.system.vo.DictModel;
import org.dfzt.common.system.vo.DynamicDataSourceModel;
import org.dfzt.common.util.BrowserUtils;
import org.dfzt.common.util.oConvertUtils;
import org.dfzt.modules.online.cgreport.entity.OnlCgreportHead;
import org.dfzt.modules.online.cgreport.entity.OnlCgreportItem;
import org.dfzt.modules.online.cgreport.entity.OnlCgreportParam;
import org.dfzt.modules.online.cgreport.mapper.OnlCgreportHeadMapper;
import org.dfzt.modules.online.cgreport.service.IOnlCgreportItemService;
import org.dfzt.modules.online.cgreport.service.IOnlCgreportParamService;
import org.dfzt.modules.online.cgreport.service.impl.OnlCgreportHeadServiceImpl;
import org.dfzt.modules.online.cgreport.util.SqlUtil;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController("onlCgreportAPI")
@RequestMapping({"/online/cgreport/api"})
public class OnlCgreportAPIController {
    private static final Logger a = LoggerFactory.getLogger(OnlCgreportAPIController.class);


    @Autowired
    private OnlCgreportHeadServiceImpl onlCgreportHeadService;


    @Autowired
    private IOnlCgreportItemService onlCgreportItemService;


    @Autowired
    private ISysBaseAPI sysBaseAPI;


    @Autowired
    private IOnlCgreportParamService onlCgreportParamService;


    @GetMapping({"/getColumnsAndData/{code}"})
    @PermissionData
    public Result<?> a(@PathVariable("code") String paramString, HttpServletRequest paramHttpServletRequest) {
        OnlCgreportHead onlCgreportHead = (OnlCgreportHead) this.onlCgreportHeadService.getById(paramString);
        if (onlCgreportHead == null) {
            return Result.error("实体不存在");
        }

        Result result = b(paramString, paramHttpServletRequest);
        if (result.getCode().equals(Integer.valueOf(200))) {

            JSONObject jSONObject = JSON.parseObject(JSONObject.toJSONString(result.getResult()));
            JSONArray jSONArray1 = jSONObject.getJSONArray("records");


            QueryWrapper queryWrapper = new QueryWrapper();
            ((QueryWrapper) ((QueryWrapper) queryWrapper.eq("cgrhead_id", paramString)).eq("is_show", Integer.valueOf(1))).orderByAsc("order_num");


            List<OnlCgreportItem> list = this.onlCgreportItemService.list(queryWrapper);


            HashMap hashMap1 = new HashMap();

            JSONArray jSONArray2 = new JSONArray();

            JSONArray jSONArray3 = new JSONArray();
            for (OnlCgreportItem onlCgreportItem : list) {
                JSONObject jSONObject1 = new JSONObject(4);
                jSONObject1.put("title", onlCgreportItem.getFieldTxt());
                jSONObject1.put("dataIndex", onlCgreportItem.getFieldName());
                jSONObject1.put("align", "center");
                jSONObject1.put("sorter", "true");

                if (StringUtils.isNotBlank(onlCgreportItem.getFieldHref())) {
                    String str1 = "fieldHref_" + onlCgreportItem.getFieldName();
                    JSONObject jSONObject2 = new JSONObject();
                    jSONObject2.put("customRender", str1);
                    jSONObject1.put("scopedSlots", jSONObject2);

                    JSONObject jSONObject3 = new JSONObject();
                    jSONObject3.put("slotName", str1);
                    jSONObject3.put("href", onlCgreportItem.getFieldHref());
                    jSONArray2.add(jSONObject3);
                }

                jSONArray3.add(jSONObject1);


                String str = onlCgreportItem.getDictCode();
                List list1 = a(str, jSONArray1, onlCgreportItem.getFieldName());
                if (list1 != null) {
                    hashMap1.put(onlCgreportItem.getFieldName(), list1);
                    jSONObject1.put("customRender", onlCgreportItem.getFieldName());
                }
            }


            HashMap hashMap2 = new HashMap(3);
            hashMap2.put("data", result.getResult());
            hashMap2.put("columns", jSONArray3);
            hashMap2.put("dictOptions", hashMap1);
            hashMap2.put("fieldHrefSlots", jSONArray2);
            hashMap2.put("cgreportHeadName", onlCgreportHead.getName());

            return Result.ok(hashMap2);
        }
        return result;
    }


    private List<DictModel> a(String paramString1, JSONArray paramJSONArray, String paramString2) {
        List list = null;
        if (oConvertUtils.isNotEmpty(paramString1)) {
            if (paramString1.trim().toLowerCase().indexOf("select ") == 0 && (paramString2 == null || paramJSONArray.size() > 0)) {


                paramString1 = paramString1.trim();
                int i = paramString1.lastIndexOf(";");
                if (i == paramString1.length() - 1) {
                    paramString1 = paramString1.substring(0, i);
                }

                String str = "SELECT * FROM (" + paramString1 + ") temp ";

                if (paramJSONArray != null) {
                    ArrayList arrayList = new ArrayList();
                    for (byte b1 = 0; b1 < paramJSONArray.size(); b1++) {
                        JSONObject jSONObject = paramJSONArray.getJSONObject(b1);
                        String str2 = jSONObject.getString(paramString2);
                        if (StringUtils.isNotBlank(str2)) {
                            arrayList.add(str2);
                        }
                    }
                    String str1 = "'" + StringUtils.join(arrayList, "','") + "'";
                    str = str + "WHERE temp.value IN (" + str1 + ")";
                }
                List list1 = ((OnlCgreportHeadMapper) this.onlCgreportHeadService.getBaseMapper()).executeSelete(str);
                if (list1 != null && list1.size() != 0) {
                    String str1 = JSON.toJSONString(list1);
                    list = JSON.parseArray(str1, DictModel.class);
                }
            } else {
                list = this.sysBaseAPI.queryDictItemsByCode(paramString1);
            }
        }
        return list;
    }


    @Deprecated
    @GetMapping({"/getColumns/{code}"})
    public Result<?> a(@PathVariable("code") String paramString) {
        OnlCgreportHead onlCgreportHead = (OnlCgreportHead) this.onlCgreportHeadService.getById(paramString);
        if (onlCgreportHead == null) {
            return Result.error("实体不存在");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("cgrhead_id", paramString);
        queryWrapper.eq("is_show", Integer.valueOf(1));
        queryWrapper.orderByAsc("order_num");

        List<OnlCgreportItem> list = this.onlCgreportItemService.list(queryWrapper);

        ArrayList arrayList = new ArrayList();
        HashMap hashMap1 = new HashMap();
        for (OnlCgreportItem onlCgreportItem : list) {
            HashMap hashMap = new HashMap(3);
            hashMap.put("title", onlCgreportItem.getFieldTxt());
            hashMap.put("dataIndex", onlCgreportItem.getFieldName());
            hashMap.put("align", "center");
            hashMap.put("sorter", "true");
            arrayList.add(hashMap);


            String str = onlCgreportItem.getDictCode();

            if (oConvertUtils.isNotEmpty(str)) {
                List list1 = null;

                if (str.toLowerCase().indexOf("select ") == 0) {
                    List list2 = ((OnlCgreportHeadMapper) this.onlCgreportHeadService.getBaseMapper()).executeSelete(str);
                    if (list2 != null && list2.size() != 0) {
                        String str1 = JSON.toJSONString(list2);
                        list1 = JSON.parseArray(str1, DictModel.class);
                    }
                } else {
                    list1 = this.sysBaseAPI.queryDictItemsByCode(str);
                }

                if (list1 != null) {
                    hashMap1.put(onlCgreportItem.getFieldName(), list1);
                    hashMap.put("customRender", onlCgreportItem.getFieldName());
                }
            }
        }


        HashMap hashMap2 = new HashMap(1);
        hashMap2.put("columns", arrayList);
        hashMap2.put("dictOptions", hashMap1);
        hashMap2.put("cgreportHeadName", onlCgreportHead.getName());

        return Result.ok(hashMap2);
    }


    @GetMapping({"/getData/{code}"})
    @PermissionData
    public Result<?> b(@PathVariable("code") String paramString, HttpServletRequest paramHttpServletRequest) {
        OnlCgreportHead onlCgreportHead = (OnlCgreportHead) this.onlCgreportHeadService.getById(paramString);
        if (onlCgreportHead == null) {
            return Result.error("实体不存在");
        }
        String str1 = onlCgreportHead.getCgrSql().trim();


        String str2 = onlCgreportHead.getDbSource();
        try {
            Map map2, map1 = SqlUtil.a(paramHttpServletRequest);

            if (StringUtils.isNotBlank(str2)) {
                a.info("Online报表: 走了多数据源逻辑");
                map2 = this.onlCgreportHeadService.executeSelectSqlDynamic(str2, str1, map1, onlCgreportHead.getId());
            } else {
                a.info("Online报表: 走了稳定逻辑");
                map2 = this.onlCgreportHeadService.executeSelectSql(str1, onlCgreportHead.getId(), map1);
            }
            return Result.ok(map2);
        } catch (Exception exception) {
            a.error(exception.getMessage(), exception);
            return Result.error("SQL执行失败：" + exception.getMessage());
        }
    }


    @GetMapping({"/getQueryInfo/{code}"})
    public Result<?> b(@PathVariable("code") String paramString) {
        try {
            List list = this.onlCgreportItemService.getAutoListQueryInfo(paramString);
            return Result.ok(list);
        } catch (Exception exception) {
            a.info(exception.getMessage(), exception);
            return Result.error("查询失败");
        }
    }


    @GetMapping({"/getParamsInfo/{code}"})
    public Result<?> c(@PathVariable("code") String paramString) {
        try {
            LambdaQueryWrapper<OnlCgreportParam> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OnlCgreportParam::getCgrheadId, paramString);
            List list = this.onlCgreportParamService.list(lambdaQueryWrapper);
            return Result.ok(list);
        } catch (Exception exception) {
            a.info(exception.getMessage(), exception);
            return Result.error("查询失败");
        }
    }


    @PermissionData
    @RequestMapping({"/exportXls/{reportId}"})
    public void a(@PathVariable("reportId") String paramString, HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse) {
        String str1 = "报表";
        String str2 = "导出信息";
        if (oConvertUtils.isNotEmpty(paramString)) {
            Map map = null;
            try {
                map = this.onlCgreportHeadService.queryCgReportConfig(paramString);
            } catch (Exception exception) {
                throw new SpringBootException("动态报表配置不存在!");
            }
            List list1 = (List) map.get("items");

            Result result = b(paramString, paramHttpServletRequest);
            List list2 = null;
            if (result.getCode().equals(Integer.valueOf(200))) {
                Map map1 = (Map) result.getResult();
                list2 = (List) map1.get("records");
            }


            ArrayList arrayList = new ArrayList();
            for (byte b1 = 0; b1 < list1.size(); b1++) {

                if ("1".equals(oConvertUtils.getString(((Map) list1.get(b1)).get("is_show")))) {

                    String str = ((Map) list1.get(b1)).get("field_name").toString();
                    ExcelExportEntity excelExportEntity = new ExcelExportEntity(((Map) list1.get(b1)).get("field_txt").toString(), str, 15);


                    Object object1 = ((Map) list1.get(b1)).get("dict_code");
                    JSONArray jSONArray = JSONObject.parseArray(JSONObject.toJSONString(list2));
                    List<DictModel> list = a(oConvertUtils.getString(object1), jSONArray, str);
                    if (list != null && list.size() > 0) {
                        ArrayList arrayList1 = new ArrayList();
                        for (DictModel dictModel : list) {
                            arrayList1.add(dictModel.getText() + "_" + dictModel.getValue());
                        }

                        excelExportEntity.setReplace((String[]) arrayList1.toArray(new String[arrayList1.size()]));
                    }


                    Object object2 = ((Map) list1.get(b1)).get("replace_val");
                    if (oConvertUtils.isNotEmpty(object2)) {
                        excelExportEntity.setReplace(object2.toString().split(","));
                    }
                    arrayList.add(excelExportEntity);
                }
            }


            paramHttpServletResponse.setContentType("application/vnd.ms-excel");
          ServletOutputStream servletOutputStream = null;


            try {
                String str = BrowserUtils.checkBrowse(paramHttpServletRequest);
                if ("MSIE".equalsIgnoreCase(str.substring(0, 4))) {
                    paramHttpServletResponse.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(str1, "UTF-8") + ".xls");
                } else {
                    String str3 = new String(str1.getBytes("UTF-8"), "ISO8859-1");
                    paramHttpServletResponse.setHeader("content-disposition", "attachment;filename=" + str3 + ".xls");
                }


                Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(null, str2), arrayList, list2);
                servletOutputStream = paramHttpServletResponse.getOutputStream();
                workbook.write(servletOutputStream);
            } catch (Exception exception) {

              try {
                servletOutputStream.flush();
              } catch (IOException e) {
                e.printStackTrace();
              }
              try {
                servletOutputStream.close();
              } catch (IOException e) {
                e.printStackTrace();
              }

            } finally {
                try {
                    servletOutputStream.flush();
                    servletOutputStream.close();
                } catch (Exception exception) {
                }
            }


        } else {

            throw new SpringBootException("参数错误");
        }
    }


    @GetMapping({"/getRpColumns/{code}"})
    public Result<?> d(@PathVariable("code") String paramString) {
        LambdaQueryWrapper<OnlCgreportHead> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OnlCgreportHead::getCode, paramString);
        OnlCgreportHead onlCgreportHead = (OnlCgreportHead) this.onlCgreportHeadService.getOne(lambdaQueryWrapper);
        if (onlCgreportHead == null) {
            return Result.error("实体不存在");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("cgrhead_id", onlCgreportHead.getId());
        queryWrapper.eq("is_show", Integer.valueOf(1));
        queryWrapper.orderByAsc("order_num");

        List<OnlCgreportItem> list = this.onlCgreportItemService.list(queryWrapper);

        ArrayList arrayList = new ArrayList();
        HashMap hashMap1 = new HashMap();
        for (OnlCgreportItem onlCgreportItem : list) {
            HashMap hashMap = new HashMap(3);
            hashMap.put("title", onlCgreportItem.getFieldTxt());
            hashMap.put("dataIndex", onlCgreportItem.getFieldName());
            hashMap.put("align", "center");

            String str1 = onlCgreportItem.getFieldType();
            if ("Integer".equals(str1) || "Date".equals(str1) || "Long".equals(str1)) {
                hashMap.put("sorter", "true");
            }


            String str2 = onlCgreportItem.getDictCode();
            if (oConvertUtils.isNotEmpty(str2)) {
                List list1 = a(onlCgreportItem.getDictCode(), (JSONArray) null, null);
                hashMap1.put(onlCgreportItem.getFieldName(), list1);
                hashMap.put("customRender", onlCgreportItem.getFieldName());
            }
            arrayList.add(hashMap);
        }

        HashMap hashMap2 = new HashMap(1);
        hashMap2.put("columns", arrayList);
        hashMap2.put("dictOptions", hashMap1);
        hashMap2.put("cgRpConfigId", onlCgreportHead.getId());
        hashMap2.put("cgRpConfigName", onlCgreportHead.getName());
        return Result.ok(hashMap2);
    }


    @PostMapping({"/testConnection"})
    public Result a(@RequestBody DynamicDataSourceModel paramDynamicDataSourceModel) {
      Connection connection = null;
        try {
            Class.forName(paramDynamicDataSourceModel.getDbDriver());

            connection = DriverManager.getConnection(paramDynamicDataSourceModel.getDbUrl(), paramDynamicDataSourceModel.getDbUsername(), paramDynamicDataSourceModel.getDbPassword());
            if (connection != null) {
                return Result.ok("数据库连接成功");
            }
            return Result.ok("数据库连接失败：错误未知");
        } catch (ClassNotFoundException classNotFoundException) {
            a.error(classNotFoundException.toString());
            return Result.error("数据库连接失败：驱动类不存在");
        } catch (Exception exception) {
            a.error(exception.toString());
            return Result.error("数据库连接失败：" + exception.getMessage());
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (SQLException sQLException) {
                a.error(sQLException.toString());
            }
        }
    }
}
